import React, { Component } from "react"
import { TransitionGroup, CSSTransition } from "react-transition-group"

export class TransitionGroupTest extends Component {
  state = {
    list: ['item1','item2']
  }

  handleAddItem = () => {
    this.setState(state => ({
      list: [...state.list, "item"]
    }))
  }
  
  handleDeleteItem = (index) => {
    this.setState(state => ({
      list: [...this.state.list.filter((item, i) => index !== i)]
    }))
  }

  render() {
    return (
      <div>
        <TransitionGroup appear>
          {this.state.list.map((item, index) => (
            <CSSTransition
            timeout={300} //动画的执行时间，所对应的就是改变类的时间，所以最好 transition-time 和这个值是相对应的
            classNames={"fade"} //动画过程中添加所添加类名的前缀
            unmountOnExit //当出场动画执行完毕后卸载这个元素，也就是从 DOM 中删除
            key={index}
          >
            <div onClick={e => this.handleDeleteItem(index) }>
              {index} - {item}
            </div>
          </CSSTransition>
          ))}
        </TransitionGroup>
        <button onClick={this.handleAddItem}>添加元素</button>
      </div>
    )
  }
}

export default TransitionGroupTest
